/*
 * FileName: LazySingleton4.java
 * Author:   zzw
 * Date:     2018年05月07日
 * Description:
 */
package com.zzw.design.singleton;

import java.io.*;

/**
 * 〈〉<br>
 * 〈〉
 *
 * @author zzw
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本]（可选）
 */
public class LazySingleton4 implements Serializable {

    private static boolean initialized = false;
    private LazySingleton4() {
        synchronized (LazySingleton4.class) {
            if (initialized == false) {
                initialized = !initialized;
            } else {
                throw new RuntimeException("单例已被破坏");
            }
        }
    }
    static class SingletonHolder {
        private static final LazySingleton4 instance = new LazySingleton4();
    }

    public static LazySingleton4 getInstance() {
        return SingletonHolder.instance;
    }

    private Object readResolve() {
        return getInstance();
    }

    public static void main(String[] args) {
        try {
            LazySingleton4 instance1 = LazySingleton4.getInstance();
            ObjectOutput out = null;
            out = new ObjectOutputStream(new FileOutputStream("filename.ser"));
            out.writeObject(instance1);
            out.close();
            ObjectInput in = new ObjectInputStream(new FileInputStream("filename.ser"));
            LazySingleton4 instance2 = (LazySingleton4) in.readObject();
            in.close();
            System.out.println("instance1 hashCode=" + instance1.hashCode());
            System.out.println("instance2 hashCode=" + instance2.hashCode());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
